<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
	$('#orderTable').bootstrapTable({
		 
		  //请求方法
               method: 'get',
               //类型json
               dataType: "json",
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/sc/logisticsVehicle/findByPage",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               clickToSelect: true,
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	window.location = "${ctx}/sc/order/order/form?id=" + row.id;
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该订单记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/sc/order/order/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#orderTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
               columns: [{
		        checkbox: true
		       
		    }
			,{
		        field: 'vehicleType',
		        title: '车辆类型',
		        sortable: true,
		        formatter:function(value, row , index){
		        	return jp.getDictLabel(${fns:toJson(fns:getDictList('sc_logistics_vehicle_type'))}, value, "-");
		        }
		    }
			,{
		        field: 'vehicleAmount',
		        title: '车次',
		        sortable: true
		       
		    }
			,{
		        field: 'vehiclePrice',
		        title: '车辆费用',
		        sortable: true
		       
		    }
			,{
		        field: 'workerAmount',
		        title: '工人数量',
		        sortable: true
		       
		    }
			,{
		        field: 'workerPrice',
		        title: '工人费用',
		        sortable: true
		       
		    }
			,{
		        field: 'deliveryDate',
		        title: '指派日期',
		        sortable: true
		       
		    }
						
		     ]
		
		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#orderTable').bootstrapTable("toggleView");
		}
	  
	  $('#orderTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#orderTable').bootstrapTable('getSelections').length);
            $('#edit').prop('disabled', $('#orderTable').bootstrapTable('getSelections').length!=1);
        });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 1, 
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/sc/order/order/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe 
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#orderTable').bootstrapTable('refresh');
		});
	 
	  $("#add").click("click", function() {
		  jp.open({
	          type: 2,
	          area: ['60%', '70%'],
	          title: '车辆分配',     
	          maxmin: true, //开启最大化最小化按钮*!/
	          content:"${ctx}/sc/logisticsVehicle/assignList",
	          btn:['提交','关闭'],
	          yes : function(index,layero) {

	        	  var rows =$(layero).find("iframe")[0].contentWindow.$("#needAssignTable").bootstrapTable('getSelections');
	        	  var vehicleType = $(layero).find("iframe")[0].contentWindow.$("#vehicleType").val();
	        	  var vehicleAmount=$(layero).find("iframe")[0].contentWindow.$("#vehicleAmount").val();
	        	  var workerAmount=$(layero).find("iframe")[0].contentWindow.$("#workerAmount").val();
	        	  var deliveryDate=$(layero).find("iframe")[0].contentWindow.$("#assignDate").val();
	        	  var workerPrice=$(layero).find("iframe")[0].contentWindow.$("#workerPrice").val();
	        	  var vehiclePrice=$(layero).find("iframe")[0].contentWindow.$("#vehiclePrice").val();
	        	  var workerId=$(layero).find("iframe")[0].contentWindow.$("#workerId").val();
	        	  if(vehicleType == null || vehicleType==''){
	        			jp.error("请选择车辆!");
	        			return;
	        		}
	        		if(vehicleAmount == null || vehicleAmount==''){
	        			jp.error("请填写车次!");
	        			return;
	        		}
	        		if(workerAmount == null || workerAmount==''){
	        			jp.error("请填写工人数量!");
	        			return;
	        		}
	        		if(deliveryDate == null || deliveryDate==''){
	        			jp.error("请选择指派日期!");
	        			return;
	        		}
	        		if(workerPrice == null || workerPrice==''){
	        			jp.error("请填写工人费用!");
	        			return;
	        		}
	        		if(vehiclePrice == null || vehiclePrice==''){
	        			jp.error("请填写车辆费用!");
	        			return;
	        		} 
	        		if(workerId == null || workerId==''){
	        			jp.error("请填写指派司机!");
	        			return;
	        		} 
	        		var arr = new Array();
	        	    if(rows.length==0){
	        	    	jp.error('请选择项目!');
	        	    	return;
	        	    }
	        	    else{
	        	    	if(rows.length>1){
	        	    		for(var i=1;i<rows.length;i++){
	        	    			if(rows[i].customerId!=rows[i-1].customerId && vehicleAmount!=1){
	        	    				jp.error("多个项目只能选择一车次!");
	        	    				return;
	            	    		}
	        	    		}
	        	    	}
	        	    	for(var i=0;i<rows.length;i++){
	        	    		var logis = new Object();
	        	    		logis.customerId=rows[i].customerId;
	        	    		logis.serviceType=rows[i].serviceType;
	        	    		arr.push(logis);
	        	    	}
	        	    }
		        	  
	        	    $.ajax({
	        	        url: "${ctx}/sc/logisticsVehicle/save",
	        	        type: "post",
	        	        dataType:"JSON",
	        	        data:{
	        	        	vehicleType:vehicleType,
	        	        	vehicleAmount:vehicleAmount,
	        	    	 	workerAmount:workerAmount,
	        	    	 	deliveryDate:deliveryDate,
	        	    		 workerPrice:workerPrice,
	        	    		vehiclePrice:vehiclePrice,
	        	    		workerId:workerId,
	        	    		arr:JSON.stringify(arr)
	        	        },
	        	        beforeSend: function () {
	        	        	jp.close(index);
	        	            index1 = layer.load(1, {
	        	                shade: [0.5, '#fff'] //0.1透明度的白色背景
	        	            });
	        	        },
	        	        complete: function () {
	        	            layer.close(index1);
	        	        },
	        	        success: function (data) {

	        	            if (data== "1") {
	        	                layer.alert('保存成功!', {icon: 1, closeBtn: 0},function (){
	        	                	window.location.reload();
	        	                });
	        	            }
	        	        },
	        	        error: function (e) {
	        	            layer.alert('保存失败!', {
	        	                icon: 2,
	        	                title: "提示"
	        	            });

	        	        }
	        	    });
	        	    
	          }
		  })
		});
	  
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		  $("#searchForm  .select-item").html("");
		  $('#orderTable').bootstrapTable('refresh');
		});
		
		$('#beginCreateTime').datetimepicker({
			 format: "YYYY-MM-DD HH:mm:ss"
		});
		$('#endCreateTime').datetimepicker({
			 format: "YYYY-MM-DD HH:mm:ss"
		});
		
	});
		
  function openOrderDetail(id){
	  jp.open({
          type: 2,
          area: ['96%', '96%'],
          title: '订单详情',     
          maxmin: true, //开启最大化最小化按钮*!/
          content:"${ctx}/sc/order/order/orderDetail?orderId="+id
	  })
  }

  function getIdSelections() {
        return $.map($("#orderTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
  
  function deleteAll(){

		jp.confirm('确认要删除该订单记录吗？', function(){
			jp.loading();  	
			jp.get("${ctx}/sc/order/order/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#orderTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})
          	   
		})
  }
  function edit(){
	  window.location = "${ctx}/sc/order/order/form?id=" + getIdSelections();
  }
  
</script>